package cn.xiaopengstack.trigger.listener;

import cn.xiaopengstack.domain.order.model.entity.OrderUpdateEntity;
import cn.xiaopengstack.domain.order.service.IOrderService;
import cn.xiaopengstack.domain.pay.event.PayResultHandelEvent;
import cn.xiaopengstack.types.event.BaseEvent;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author jiangyangang
 */
@RocketMQMessageListener(
        topic = "alipay_success_notify",
        consumerGroup = "s-pay-small-group",
        selectorType = SelectorType.TAG,
        selectorExpression = "*"
)
@Component
@Slf4j
public class SendAlipayResultConsumer implements RocketMQListener<String> {

    @Resource
    private IOrderService orderService;

    @Override
    public void onMessage(String message) {
        try {
            BaseEvent.EventMessage<PayResultHandelEvent.PayResultMessage> eventMessage = JSONObject.parseObject(message, new TypeReference<BaseEvent.EventMessage<PayResultHandelEvent.PayResultMessage>>() {
            });
            PayResultHandelEvent.PayResultMessage resultMessage = eventMessage.getMessage();
            // 更新订单
            orderService.updateOrder(OrderUpdateEntity.builder()
                            .userId(resultMessage.getUserId())
                            .payTime(resultMessage.getPayTime())
                            .payOrderId(resultMessage.getPayOrderId())
                            .build());

        } catch (Exception e) {
            log.error("支付宝支付通知消息消费失败;topic={}, message={}", "alipay_success_notify", message, e);
            throw e;
        }
    }
}
